package com.example.service.impl;


import com.example.constant.NumConstant;
import com.example.entity.RecommendGoods;
import com.example.mapper.RecommendGoodsMapper;
import com.example.service.RecommendGoodsService;
import com.example.vo.IndexRecommendVo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RecommendGoodsServiceImpl implements RecommendGoodsService {
    @Autowired
    private RecommendGoodsMapper recommendGoodsMapper;

    @Override
    public IndexRecommendVo getIndexRecommendGoods() {
        List<RecommendGoods> recommendGoods = recommendGoodsMapper.getAllEnableGoods(NumConstant.STATUS_ENABLE);
        HashMap<Integer, List<RecommendGoods>> map = new HashMap<>();
        recommendGoods.forEach(rg->{
            Integer type = rg.getType();
            if(!map.containsKey(type)){
                ArrayList<RecommendGoods> list = new ArrayList<>();
                map.put(type,list);
            }
            map.get(type).add(rg);
        });
        IndexRecommendVo indexRecommendVo = new IndexRecommendVo();
        String[] names = {"top","middleLeft","middle","middleRight","bottom"};
        for(Integer type : map.keySet()){
            String fieldName = names[type-1];
            List<RecommendGoods> valList = map.get(type);
            if(valList.size() > 4){
                valList = valList.subList(0,4);
            }
            try {
                Field field = indexRecommendVo.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                field.set(indexRecommendVo,valList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return indexRecommendVo;
    }
}